<?php 

namespace controladores;

use fcf\Controller as Controller,
	fcf\view as View,
	dao\usuariosDao as usuariosDao,
	dao\logsDao as logsDao,
    dao\galeriasDao as galeriasDao,
	utils\Utils;


class Galerias extends Controller{
        
	
    public function galerias(){
		$this->checkSesion();
		$query = new galeriasDao();
        $galeries = $query->get_galeries();
        $data['seccions'] = $galeries;
		View::render('','galerias/galerias', $data);
	} 
    
    public function galeria($id){
		$this->checkSesion();
		$query = new galeriasDao();
        $fotos = $query->get_fotos($id);
        $galeria = $query->get_galeria($id);
        $visible = $galeria[0]->visible;
        $estado = '';
        if($visible == 1){
            $estado = 'on';
        } else {
            $estado = 'off';
        }
        $_SESSION['id_galeria'] = $galeria[0]->id;
        $_SESSION['ruta2'] = $_SERVER['DOCUMENT_ROOT'] . '/test/assets/fotos/' . $galeria[0]->nom . '/original';
        $_SESSION['ruta3'] = $_SERVER['DOCUMENT_ROOT'] . '/test/assets/fotos/' . $galeria[0]->nom . '/web';
        $seccion = $query->get_seccio($galeria[0]->seccion);
        $data['seccio'] = $seccion[0]->nom;
        $data['galeria'] = $galeria;
        $data['estado'] = $estado;
        $data['fotos'] = $fotos;
        $data['id'] = $id;
		View::render('','galerias/galeria', $data);
	} 
    
    public function activar_galeria(){
		$this->checkSesion();
		$query = new galeriasDao();
        $id = $_POST['id'];
        $estado = $_POST['estado'];
        $query->activar_galeria($id, $estado);
	} 
    
    public function seccions(){
		$this->checkSesion();
		$query = new galeriasDao();
        $data['seccions'] = $query->get_seccions();
		View::render('','galerias/seccions', $data);
	} 
    
    public function crearSeccion(){
		$this->checkSesion();
		$query = new galeriasDao();
        $query->crear_seccion($_POST['seccion']);

	} 
    
	public function novaGaleria(){
		$this->checkSesion();
		$query = new galeriasDao();
        $seccions = $query->get_seccions();   
        $data['seccions'] = $seccions; 
		View::render('','galerias/nova_galeria', $data);
	} 

	public function subirFotos(){
		$query = new galeriasDao();
        $ruta = $_POST['ruta'];
        echo $ruta;
        exit();
        $id_galeria = $_SESSION['id_galeria'];
        $ruta2 = $_SESSION['ruta2'];
        $ruta3 = $_SESSION['ruta3'];
        $data = date("Y-m-d H:i:s");
        $query->subir_fotos($_FILES['file']['name'], $_FILES['file']['type'], $_FILES['file']['size'], $id_galeria);
        if (!empty($_FILES)) { 
            $tempFile = $_FILES['file']['tmp_name'];
 
            $mainFile = $ruta2 . '/' . $_FILES['file']['name']; 
            
            echo $mainFile;
            
            move_uploaded_file($tempFile,$mainFile); 
            $this->redimensionar($ruta3, $mainFile);
        }  
	} 
    
    public function get_foto($id){
		$this->checkSesion();
		$query = new galeriasDao();
        $foto = $query->get_foto($id);   
        return $foto;
	} 
    
    public function borrar_foto($id){
		$this->checkSesion();
		$query = new galeriasDao();
        $foto = $this->get_foto($id);
        print_r($foto);
        exit();
        $query->borrar_foto($id);   
        echo 'ok';
	} 
    
    public function eliminarGaleria(){
		$this->checkSesion();
		$query = new galeriasDao();
        $id = $_POST['id'];
        $tipo = $_POST['tipo'];
        if(($tipo) == 'seccion'){
            if($query->eliminar_galeria($id)){
                
            }
        } 
	} 
	
    public function crearGaleria(){
		$this->checkSesion();
		$query = new galeriasDao();
        if($query->galeria_exist($_POST['nombre']) == 0){
            $id = $query->crear_galeria($_POST['nombre'], $_POST['seccion']);
        } else {
            exit();
        }
        $ruta = $_SERVER['DOCUMENT_ROOT'] . '/test/assets/fotos/' . $_POST['nombre'];
        $ruta2 = $_SERVER['DOCUMENT_ROOT'] . '/test/assets/fotos/' . $_POST['nombre'] . '/original';
        $ruta3 = $_SERVER['DOCUMENT_ROOT'] . '/test/assets/fotos/' . $_POST['nombre'] . '/web';
        
        $_SESSION['id_galeria'] = $id[0]->id;
        $_SESSION['ruta2'] = $ruta2;
        $_SESSION['ruta3'] = $ruta3;
		if(!file_exists($ruta)){
            if(mkdir($ruta)){
                mkdir($ruta2);
                mkdir($ruta3);
            }
            
            echo "Se ha creado el directorio:" . $ruta2;
        } else {
            echo "la ruta:" . $ruta2 . "ya existe";
        }
	} 
    
    function redimensionar($ruta, $foto){
		
		
		if(isset($_POST)){
			############ Edit settings ##############
			$ThumbSquareSize 		= 100; //Thumbnail will be 200x200
			$BigImageMaxSize 		= 200; //Image Maximum height or width
			$ThumbPrefix			= "thumb_"; //Normal thumb Prefix
			$DestinationDirectory = $ruta . '/';
			$Quality 				= 70; //jpeg quality
			##########################################
			//check if this is an ajax request
			if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){ die(); 	}
				// Random number will be added after image name
				$RandomNumber 	= rand(0, 9999999999);
				$ImageName 		= str_replace(' ','-',strtolower($_FILES['file']['name'])); //get image name
				
				
				$ImageSize 		= $_FILES['file']['size']; // get original image size
				$TempSrc	 	= $foto; // Temp name of image file stored in PHP tmp folder
				$ImageType	 	= $_FILES['file']['type']; //get file type, returns "image/png", image/jpeg, text/plain etc.
	
				list($w, $h, $type, $attr) = getimagesize($foto);
				/*
				if($w != '665' || $h != '415'){ 
				    $info['error'] = true;
					$info['mensaje'] = 'La imagen ha de ser de 665x415px';
					return Response::json($info);
				}*/
			//Let's check allowed $ImageType, we use PHP SWITCH statement here
			switch(strtolower($ImageType)){
				case 'image/png':
					//Create a new image from file
					$CreatedImage =  imagecreatefrompng($foto);
					break;
				case 'image/gif':
					$CreatedImage =  imagecreatefromgif($foto);
					break;
				case 'image/jpeg':
				case 'image/pjpeg':
					$CreatedImage = imagecreatefromjpeg($foto);
					break;
				default:
					$info['error'] = true;
					$info['mensaje'] = 'Unsupported File!';
					return Response::json($info);
			}
		
			//PHP getimagesize() function returns height/width from image file stored in PHP tmp folder.
			//Get first two values from image, width and height.
			//list assign svalues to $CurWidth,$CurHeight
			list($CurWidth,$CurHeight)=getimagesize($TempSrc);
		
			//Get file extension from Image name, this will be added after random name
			$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
			$ImageExt = str_replace('.','',$ImageExt);
		
			//remove extension from filename
			$ImageName 		= preg_replace("/\\.[^.\\s]{3,4}$/", "", $ImageName);
			//Construct a new name with random number and extension.
			$NewImageName = $ImageName. '.' . $ImageExt;
			//set the Destination Image
			$thumb_DestRandImageName 	= $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumbnail name with destination directory
			$DestRandImageName 			= $DestinationDirectory.$NewImageName; // Image with destination directory
			//Resize image to Specified Size by calling resizeImage function.
			
				if($this->resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType)){
					
					$info[0]['thumbnail'] = $ThumbPrefix.$NewImageName;
					//$info[0]['image'] = $NewImageName;
					return 'ok';
				}else{
					die('Resize Error'); //output error
				}
			}	 
		}
	
		
		// This function will proportionally resize image
		function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType){
			$this->layout = '';
			
			//Check Image size is not 0
			if($CurWidth <= 0 || $CurHeight <= 0){
				return false;
			}
		
			//Construct a proportional size of new image
			$ImageScale      	= min($MaxSize/$CurWidth, $MaxSize/$CurHeight);
			$NewWidth  			= ceil($ImageScale*$CurWidth);
			$NewHeight 			= ceil($ImageScale*$CurHeight);
			$NewCanves 			= imagecreatetruecolor($NewWidth, $NewHeight);
			
			imagecolortransparent($NewCanves, imagecolorallocatealpha($NewCanves, 0, 0, 0, 127));
			imagealphablending($NewCanves, false);
			imagesavealpha($NewCanves, true);
			// Resize Image
			if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0,0, $NewWidth, $NewHeight, $CurWidth, $CurHeight)){
				switch(strtolower($ImageType)){
					case 'image/png':
						imagepng($NewCanves,$DestFolder);
						break;
					case 'image/gif':
						imagegif($NewCanves,$DestFolder);
						break;
					case 'image/jpeg':
					case 'image/pjpeg':
						imagejpeg($NewCanves,$DestFolder,$Quality);
						break;
					default:
						return false;
				}
				//Destroy image, frees memory
				if(is_resource($NewCanves)) {
					imagedestroy($NewCanves);
				}
				return true;
			}
		
		}
	
}

?>